package org.csu.mypetstore.persistence.impl;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.persistence.CartItemDAO;

import java.util.List;

public class CartItemDAOImpl extends BaseDAO<CartItem> implements CartItemDAO {
    private static final String GET_CART_ITEM_BY_ACCOUNT = "SELECT * FROM cart WHERE buyername = ?";
    private static final String INSERT_CART_ITEM = "INSERT INTO cart (itemid,productid,descn,instock,quantity,listprice,totalprice,buyername) VALUES (?,?,?,?,?,?,?,?)";
    private static final String GET_CART_ITEM_BY_ID = "SELECT * FROM cart WHERE itemid = ?";
    private static final String INCREASE_CART_ITEM_QUANTITY = "UPDATE cart SET quantity = quantity + 1, totalprice = listprice * quantity WHERE buyername = ? AND itemid = ?";
    private static final String REMOVE_CART_ITEM = "DELETE FROM cart WHERE itemid = ? AND buyername = ?";
    public static final String UPDATE_CART_ITEM_QUANTITY = "UPDATE cart SET quantity = ?, totalprice = listprice * quantity WHERE buyername = ? AND itemid = ?";
    public static final String CLEAR_CART = "DELETE FROM cart WHERE buyername = ?";

    @Override
    public List<CartItem> getCartItemByAccount(Account account) {
        return queryMulti(GET_CART_ITEM_BY_ACCOUNT,CartItem.class,account.getUsername());
    }

    @Override
    public void clearCart(Account account) {
        update(CLEAR_CART,account.getUsername());
    }

    @Override
    public void insertCartItem(CartItem cartItem) {
        update(INSERT_CART_ITEM,cartItem.getItemId(),cartItem.getProductId(),cartItem.getDescn(),cartItem.isInStock(),cartItem.getQuantity(),cartItem.getListPrice(),cartItem.getTotalPrice(),cartItem.getBuyerName());
    }

    @Override
    public CartItem getCartItemById(String itemId) {
        return querySingle(GET_CART_ITEM_BY_ID,CartItem.class,itemId);
    }

    @Override
    public void increaseCartItemQuantity(CartItem cartItem) {
        update(INCREASE_CART_ITEM_QUANTITY,cartItem.getBuyerName(),cartItem.getItemId());
    }

    @Override
    public void removeCartItem(CartItem cartItem) {
        update(REMOVE_CART_ITEM,cartItem.getItemId(),cartItem.getBuyerName());
    }

    @Override
    public void updateCartItemQuantity(CartItem cartItem) {
        update(UPDATE_CART_ITEM_QUANTITY,cartItem.getQuantity(),cartItem.getBuyerName(),cartItem.getItemId());
    }
}
